package com.ghsc.ghxc.jsb.utils

import android.content.Context
import android.content.res.Resources
import android.graphics.Bitmap
import android.os.Environment
import android.text.TextUtils
import android.util.Base64
import android.util.TypedValue
import com.cn.appcore.config.AppConfig
import com.cn.appcore.ext.loge
import com.ghsc.ghxc.jsb.config.CustKey
import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import kotlin.math.max
import kotlin.math.min
import java.util.Date as Date1

/**
 * 项目：sociallive
 * 包名：com.cn.sociallive.utils
 * 类名：StringUtil
 * 创建时间：2022/5/26 2:48 下午
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class StringUtil {
    companion object{
        //屏幕的宽度
        fun screenWidth():Int{
            return  AppConfig.getApplication().resources.displayMetrics.widthPixels
        }
        //屏幕的密度
        fun screenDensity():Float{
            return AppConfig.getApplication().resources.displayMetrics.density
        }
        //手机正则
        fun isChinaPhoneLegal(str: String?): Boolean {
            if (str == null) {
                return false
            }
            if (str.length != 11) {
                return false
            }
            val regExp = "^((1[0-9][0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$"
            val p = Pattern.compile(regExp)
            val m = p.matcher(str)
            return m.matches()
        }


        //保留4位
        fun getToText4(double: Double): String {
            if (double>0)
                return String.format("%.4f", double)
            else return "0.0000"
        }
        //保留4位
        fun getToText4(str: String): String {
            var dou =str.toDouble()
            if (dou>0)
                return String.format("%.4f", dou)
            else return "0.0000"
        }

        /**
         * 获取时间
         */
        fun getTime(): String? {
            val sdf = SimpleDateFormat("yyyy-MM-dd")
            val date = Date1()
            return sdf.format(date)
        }
        /**
         * 获取时间
         */
        fun getTimeNianYueRi(): String? {
            val sdf = SimpleDateFormat("yyyy-MM-dd")
            val date = Date1()
            return sdf.format(date)
        }
        fun getTimeAllFormat(time: String): String? {
            val lon = time.toLong()
            var date: String? = null
            val df = SimpleDateFormat("yyyy-MM-dd")
            date = df.format(Date1(lon))
            return date
        }


        /**
         * lsit转字符串。带逗号 1,2,3,4,
         *
         * @param strlist
         * @return
         */
        fun convertListToString(strlist: List<String?>): String? {
            val sb = StringBuffer()
            if (strlist.size > 0) {
                for (i in strlist.indices) {
                    if (i == 0) {
                        sb.append(strlist[i])
                    } else {
                        sb.append(",").append(strlist[i])
                    }
                }
            }
            return sb.toString()
        }

        fun convertListToStringSpace(strlist: List<String?>): String? {
            val sb = StringBuffer()
            if (strlist.size > 0) {
                for (i in strlist.indices) {
                    if (i == 0) {
                        sb.append(strlist[i])
                    } else {
                        sb.append("  ").append(strlist[i])
                    }
                }
            }
            return sb.toString()
        }

        fun convertListToStringInt(strlist: List<Int?>): String? {
            val sb = StringBuffer()
            if (strlist.size > 0) {
                for (i in strlist.indices) {
                    if (i == 0) {
                        sb.append(strlist[i])
                    } else {
                        sb.append(",").append(strlist[i])
                    }
                }
            }
            return sb.toString()
        }


        fun convertListToStringWrap(strlist: List<String?>): String? {
            val sb = StringBuffer()
            if (strlist.size > 0) {
                for (i in strlist.indices) {
                    if (i == 0) {
                        sb.append(strlist[i])
                    } else {
                        sb.append("\n").append(strlist[i])
                    }
                }
            }
            return sb.toString()
        }
        /**
         * lsit转字符串。带逗号 1234
         *
         * @param strlist
         * @return
         */
        fun convertListToStr(strlist: List<String?>): String? {
            val sb = StringBuffer()
            if (strlist.size > 0) {
                for (i in strlist.indices) {
                    if (i == 0) {
                        sb.append(strlist[i])
                    } else {
                        sb.append(strlist[i])
                    }
                }
            }
            return sb.toString()
        }

        fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray? {
            val output = ByteArrayOutputStream()
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, output)
            if (needRecycle) {
                bmp.recycle()
            }
            val result: ByteArray = output.toByteArray()
            try {
                output.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return result
        }

        /**
         * 裁剪视频本地目录路径
         */
        fun getTrimmedVideoDir(context: Context, dirName: String): String? {
            var dirPath = ""
            dirPath = if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()) {
                (context.externalCacheDir.toString() + File.separator
                        + dirName) // /mnt/sdcard/Android/data/<package name>/files/...
            } else {
                (context.cacheDir.toString() + File.separator
                        + dirName) // /data/data/<package name>/files/...
            }
            val file = File(dirPath)
            if (!file.exists()) {
                file.mkdirs()
            }
            return dirPath
        }

        /**
         * 多个字符串拼接
         */
        fun contact(vararg args: String?): String? {
            var  stringBuffer =StringBuilder()
            stringBuffer.delete(0, stringBuffer.length)
            for (s in args) {
                stringBuffer.append(s)
            }
            //        L.e("---contact--"+sStringBuilder.toString());
            return stringBuffer.toString()
        }

         fun dp2px(dp: Float): Float {
            val r = Resources.getSystem()
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.displayMetrics)
        }

        //查询。手机型号中。是否有我们上架的型号品牌
        fun  isModel(model:String):Boolean{
//            val model = Build.MANUFACTURER.toLowerCase()
            return model.contains("xiaomi") || model.contains("mi") || model=="oppo" || model=="vivo" || model=="huawei" || model=="honor"
        }
        fun  isHuaWei(model:String):Boolean{
            return  model=="huawei" || model=="honor"
        }
        /**
         * 算出比例
         * 最大宽度  屏幕的宽度-120
         * 最小的宽度150
         *
         * 最高高度 300
         * 最小高度150
         */
        fun  imgReation(width:Float,height:Float):Float?{
            var reationValue =0f
            //屏幕的宽度
            var widthPixels= AppConfig.getApplication().resources.displayMetrics.widthPixels
            //屏幕的密度
            var density=AppConfig.getApplication().resources.displayMetrics.density

            var maxw=width/150
            var minW=width/((widthPixels/density) -120)
            var maxH=height/150
            var minH=height/300
            if(maxw<minH || maxH<minW){
                reationValue=-1f
                return reationValue
            }
            var minValue= max(minW,minH)
            var maxValue = min(maxw,maxH)
            var v = (maxValue-minValue)/2.0 + minValue
            reationValue= v.toFloat()
            return reationValue
        }



        fun bitmapToFile (bmp: Bitmap,context: Context): String?{
            val destDirPath: String? = getTrimmedVideoDir(context, "small_video.png")
            var fileOutputStream= FileOutputStream(destDirPath)
            var bos =  BufferedOutputStream(fileOutputStream)
            bmp.compress(Bitmap.CompressFormat.PNG,100,bos)
            bos.flush()
            bos.close()
            return  destDirPath
        }

        //图片bitmap转file
        fun  compressImage(bitmap: Bitmap,context: Context) :String{
            var baos =  ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
            var options = 100
            var format =  SimpleDateFormat("yyyyMMddHHmmss")
            var date = Date1(System.currentTimeMillis())
            //图片名
            var filename = format.format(date)
            var file:File?=null
            try {
               val dir = File(context.getExternalFilesDir(null)!!.path.toString() + "videoPic")
                if (!dir.exists()) {
                    dir.mkdirs()
                }
                //创建文件
                 file = File("$dir/filename.png")
                if (!file.exists()) {
                    file.createNewFile()
                }
                var fos =  FileOutputStream(file)
                fos.write(baos.toByteArray())
                fos.flush()
                fos.close()
            } catch (e: Exception) {
            }
            loge("返回="+file!!.path)
            return file.path

        }

        /**
         * 将一个数组拆分为多个数组
         * 比如[1,2,3,4,5,6,7,8]
         * 拆分为 [[1,2,3] ,[4,5,6],[7,8]]
         * 最终是嵌套 list<list<xx>>
         */
         fun <T> averageAssignFixLength(source: List<T>?, splitItemNum: Int): List<List<T>> {
            val result = ArrayList<List<T>>()

            if (source != null && source.run { isNotEmpty() } && splitItemNum > 0) {
                if (source.size <= splitItemNum) {
                    // 源List元素数量小于等于目标分组数量
                    result.add(source)
                } else {
                    // 计算拆分后list数量
                    val splitNum = if (source.size % splitItemNum == 0) source.size / splitItemNum else source.size / splitItemNum + 1

                    var value: List<T>? = null
                    for (i in 0 until splitNum) {
                        if (i < splitNum - 1) {
                            value = source.subList(i * splitItemNum, (i + 1) * splitItemNum)
                        } else {
                            // 最后一组
                            value = source.subList(i * splitItemNum, source.size)
                        }

                        result.add(value)
                    }
                }
            }

            return result
        }
        /**
         * 将一个数组拆分为多个数组
         * 比如[1,2,3,4,5,6,7,8]
         * 拆分为 [[1,2,3] ,[4,5,6],[7,8]]
         * 最终是嵌套 list<list<xx>>
         */
        fun <T> averageAssignFixLengthSize(source: List<T>?, splitItemNum: Int): Int {
            val result = ArrayList<List<T>>()
            if (source != null && source.run { isNotEmpty() } && splitItemNum > 0) {
                if (source.size <= splitItemNum) {
                    // 源List元素数量小于等于目标分组数量
                    result.add(source)
                } else {
                    // 计算拆分后list数量
                    val splitNum = if (source.size % splitItemNum == 0) source.size / splitItemNum else source.size / splitItemNum + 1

                    var value: List<T>? = null
                    for (i in 0 until splitNum) {
                        if (i < splitNum - 1) {
                            value = source.subList(i * splitItemNum, (i + 1) * splitItemNum)
                        } else {
                            // 最后一组
                            value = source.subList(i * splitItemNum, source.size)
                        }

                        result.add(value)
                    }
                }
            }

            return result.size
        }
        /**
         * 银行卡 卡号 隐藏
         */
        fun hideBankCardNumber(bankCardNumber: String): String {
            if (TextUtils.isEmpty(bankCardNumber)) {
                return ""
            }
            val length = bankCardNumber.length
            if (length < 8) {
                return bankCardNumber
            }
            val hideLength = length - 6
            val stringBuilder = java.lang.StringBuilder()
            stringBuilder.append(bankCardNumber.substring(0, 4))
            for (i in 0 until hideLength) {
                stringBuilder.append("*")
            }
            stringBuilder.append(bankCardNumber.substring(length - 2))



            val strBuilder = java.lang.StringBuilder()
            for (i in stringBuilder.indices) {
                strBuilder.append(stringBuilder[i])
                if ((i + 1) % 4 == 0 && i != length - 1) {
                    strBuilder.append(" ") // 每4位字符之间添加一个空格
                }
            }
            return strBuilder.toString()
        }


        //aes 加密
//        fun encryptAES(data: String): String {
//            val key = CustKey.APP_AES_KEY
//            val cipher = Cipher.getInstance("AES/CFB/NoPadding")
//            val secretKey = SecretKeySpec(key.toByteArray(), "AES")
//            val ivParameterSpec = IvParameterSpec(key.toByteArray())
//            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec)
//            val encryptedData = cipher.doFinal(data.toByteArray())
//            //map 转json
//            val dataAES=encodeToString(encryptedData, Base64.DEFAULT)
//            val mapK: HashMap<String, Any> = HashMap()
//            mapK["encryption"] =dataAES
//            return  GsonUtil.mapToJsonStr(mapK)!!
//        }
        //aes 解密
        fun decryptAES(key: String, encryptedData: String): String {
            val cipher = Cipher.getInstance("AES/CFB/NoPadding")
            val secretKey = SecretKeySpec(key.toByteArray(), "AES")
            val ivParameterSpec = IvParameterSpec(key.toByteArray())
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec)
            val encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT)
            val decryptedBytes = cipher.doFinal(encryptedBytes)
            return String(decryptedBytes)
        }



        //1234 5678 9012 6288
        fun addSpaceEvery4Characters(originalString: String): String? {
            if (TextUtils.isEmpty(originalString)) {
                return ""
            }
            val stringBuilder = java.lang.StringBuilder()
            val length = originalString.length
            for (i in 0 until length) {
                stringBuilder.append(originalString[i])
                if ((i + 1) % 4 == 0 && i != length - 1) {
                    stringBuilder.append(" ") // 每4位字符之间添加一个空格
                }
            }
            return stringBuilder.toString()
        }

        fun formatTimestamp(timestamp: String?): String {
            if (timestamp == null || "" == timestamp) {
                return ""
            }
            val tempTimeStamp = timestamp + "00000000000000"
            return StringBuffer(tempTimeStamp).substring(0, 14)
        }

        fun getTimeStatus(timestamp: String): String? {
            var timestamp = timestamp
            timestamp = formatTimestamp(timestamp)
            val _timestamp = timestamp.toLong()
            val curTimeMills = System.currentTimeMillis()
            val now = Calendar.getInstance()
            now.timeInMillis = curTimeMills
            val todayHoursSeconds = now[Calendar.HOUR_OF_DAY] * 60 * 60
            val todayMinutesSeconds = now[Calendar.MINUTE] * 60
            val todaySeconds = now[Calendar.SECOND]
            val todayMills = (todayHoursSeconds + todayMinutesSeconds + todaySeconds) * 1000
            val todayStartMills = curTimeMills - todayMills
            if (_timestamp >= todayStartMills) {
                if (todayStartMills - _timestamp < 60 * 1000) {
                    return "刚刚"
                } else if (todayStartMills - _timestamp < 60 * 60 * 1000) {
                    return ((todayStartMills - _timestamp) / 1000 / 60).toString() + "分钟前"
                } else if (todayStartMills - _timestamp < 24 * 60 * 60 * 1000) {
                    return ((todayStartMills - _timestamp) / 1000 / 60 / 60).toString() + "小时前"
                }
            }
            val oneDayMills = 24 * 60 * 60 * 1000
            val yesterdayStartMills = todayStartMills - oneDayMills
            if (_timestamp >= yesterdayStartMills) {
                return "昨天"
            }
            val yesterdayBeforeStartMills = yesterdayStartMills - oneDayMills
            if (_timestamp >= yesterdayBeforeStartMills) {
                return "前天"
            }
            val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
            return dateFormat.format(_timestamp)
        }

    }

}